package com.tanhua.management.controller;



import com.tanhua.common.utils.NoAuthorization;
import com.tanhua.management.service.AdminService;
import com.tanhua.management.vo.AdminVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
@Slf4j
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Value("${tanhua.mamnagement.logouturl}")
    private String logoutUrl;
    /**
     * 登录
     *
     * @param param
     * @return
     */

    @NoAuthorization
    @PostMapping("login")
        public ResponseEntity<Map<String,String>> login(@RequestBody Map<String, String> param){
        String username=param.get("username");
        String password= param.get("password");
        String verificationCode=param.get("verificationCode");
        String uuid =param.get("uuid");

        try {
            String tokenValue = this.adminService.login(username, password, verificationCode, uuid);
            if (StringUtils.isNotEmpty(tokenValue)) {
                    Map<String, String> token = new HashMap<>();
                    token.put("token", tokenValue);
                    return ResponseEntity.ok(token);
            }
        } catch (Exception e) {
           log.error("登录失败了",e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();

    }

    /**
     * 登出
     * @return
     */
    @PostMapping("logout")
    public String logout(){
        return  logoutUrl;
    }

    /**
     * 用户登录验证码图片
     */
    @NoAuthorization
    @GetMapping("/verification")
    public Void  getVerificationCode(@RequestParam("uuid") String uuid, HttpServletResponse response) throws Exception {

        try {
            this.adminService.getVerification(uuid, response);
        } catch (Exception e) {
            log.error("图片验证码生成失败~~~", e);
        }
        return null;
    }
    /**
     * 查询基本信息
     * @return
     */
    @PostMapping("profile")
    public ResponseEntity<AdminVo> adminInfo(){
        AdminVo adminVo = null;
        try {
            adminVo=adminService.adminfo();
            if (adminVo!=null){
                return ResponseEntity.ok(adminVo);
            }
        } catch (Exception e) {
            log.error("用户信息加载失败",e );
        }

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

}
